package com.bluefish.bltuan.service.impl;

import static com.bluefish.bltuan.module.mail.EmailPurpose.FIND_PASSWORD;
import static com.bluefish.bltuan.module.mail.EmailPurpose.REGISTER;
import static com.bluefish.bltuan.module.mail.EmailPurpose.SUBSCRIBER;
import static com.bluefish.bltuan.module.mail.EmailPurpose.SUBSCRIBER_NOT_YET;

import java.util.List;

import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bluefish.bltuan.cache.ApplicationConstants;
import com.bluefish.bltuan.cache.ApplicationUtils;
import com.bluefish.bltuan.module.mail.EmailTemplate;
import com.bluefish.bltuan.module.mail.Subscriber;
import com.bluefish.bltuan.module.shop.TuanGou;
import com.bluefish.bltuan.module.user.User;
import com.bluefish.bltuan.service.EmailService;
import com.bluefish.bltuan.service.ShopService;
import com.bluefish.bltuan.tools.EmailUtils;

@Service
@Transactional
public class EmailServiceImpl implements EmailService {

    private static final Logger LOG   = LoggerFactory.getLogger(EmailServiceImpl.class);

    private static final String COMMA = ",";

    private static final String UTF_8 = "UTF-8";

    private JavaMailSender      javaMailSender;

    @Resource
    private String              serviceEmail;

    private ShopService         shopService;

    public void sendEmail(String from, String to, String subject, String content) {

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, UTF_8);
        try {
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            this.javaMailSender.send(message);
        } catch (MessagingException e) {
            LOG.info(e.getMessage());
        }
    }

    public void sendEmail(String from, List<String> toList, String subject, String content) {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, UTF_8);
        String tos = getMailList(toList);
        try {
            InternetAddress[] addresses = InternetAddress.parse(tos);
            message.setRecipients(Message.RecipientType.TO, addresses);
            helper.setFrom(from);
            helper.setSubject(subject);
            helper.setText(content, true);
            this.javaMailSender.send(message);
        } catch (MessagingException e) {
            LOG.info(e.getMessage());
        }
    }

    private String getMailList(List<String> toList) {
        StringBuffer buffer = new StringBuffer();
        for (String to : toList) {
            if (to != null) {
                if (buffer.length() > 0)
                    buffer.append(COMMA);
                buffer.append(to);
            }
        }
        return buffer.toString();
    }

    public void sendRegisterEmail(User user, String activeLink, EmailTemplate template) {
        String[] values = new String[] { user.getUsername(), user.getPassword(), activeLink };
        String title = template.getTitle();
        if (title != null) {
            title = EmailUtils.generate(title, REGISTER.getVariables(), values);
        }
        String content = template.getContent();
        if (content != null) {
            content = EmailUtils.generate(content, REGISTER.getVariables(), values);
        }
        sendEmail(serviceEmail, user.getEmail(), title, content);
    }

    public void sendFindPasswordEmail(User user, String newPassword) {
        EmailTemplate template = ApplicationUtils.get(ApplicationConstants.FIND_PASSWORD_TEMPLATE);
        String[] values = new String[] { user.getUsername(), newPassword };
        String title = template.getTitle();
        if (title != null) {
            title = EmailUtils.generate(title, FIND_PASSWORD.getVariables(), values);
        }
        String content = template.getContent();
        if (content != null) {
            content = EmailUtils.generate(content, FIND_PASSWORD.getVariables(), values);
        }
        sendEmail(serviceEmail, user.getEmail(), title, content);
    }

    public void sendSubscriberEmail(Subscriber subscriber) {
        EmailTemplate template = ApplicationUtils.get(ApplicationConstants.SUBSCRIBER_TEMPLATE);
        TuanGou tuanGou = this.shopService.getTuangouToday(subscriber.getCity());
        if (tuanGou == null) {
            tuanGou = new TuanGou();
        }
        String title = template.getTitle();
        String[] values = new String[] { subscriber.getEmail(), tuanGou.getName(),
                tuanGou.getDetail() };
        if (title != null) {
            title = EmailUtils.generate(title, SUBSCRIBER.getVariables(), values);
        }
        String content = template.getContent();
        if (content != null) {
            content = EmailUtils.generate(content, SUBSCRIBER_NOT_YET.getVariables(), values);
        }
        sendEmail(serviceEmail, subscriber.getEmail(), title, content);
    }

    public void sendSubscriberNotYetEmail(Subscriber subscriber) {
        EmailTemplate template = ApplicationUtils
            .get(ApplicationConstants.SUBSCRIBER_NOT_YET_TEMPLATE);
        String title = template.getTitle();
        String[] values = new String[] { subscriber.getEmail(), template.getTitle(),
                template.getContent() };
        if (title != null) {
            title = EmailUtils.generate(title, SUBSCRIBER_NOT_YET.getVariables(), values);
        }
        String content = template.getContent();
        if (content != null) {
            content = EmailUtils.generate(content, SUBSCRIBER_NOT_YET.getVariables(), values);
        }
        sendEmail(serviceEmail, subscriber.getEmail(), title, content);
    }

    public EmailServiceImpl() {

    }

    public EmailServiceImpl(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    public void setJavaMailSender(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    public void setServiceEmail(String serviceEmail) {
        this.serviceEmail = serviceEmail;
    }

    public void setShopService(ShopService shopService) {
        this.shopService = shopService;
    }
}
